/*
 * @Description: 格式转换登记上下文
 * @Author: Rfan
 * @Date: 2022-11-19 16:12:07
 * @LastEditTime: 2022-11-19 16:21:10
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import {
  ADD_REG_CONVERSION,
  EDIT_REG_CONVERSION,
  SET_REG_CONVERSION_LIST,
  DELETE_REGISTRATION_ITEM,
  SET_SELECTED_ITEM
} from '../constants';
import { ConversionReducer } from '../reducers/ConversionReducer';
import { message, Modal } from 'antd';
import {
  addRegConversion,
  deleteRegConversionItem,
  editRegConversion,
  fetchRegConversionListByPage
} from '@/api/registration/conversion';

const initialState = {
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  selectFondId: 0,
  selectATId: 0,
  // 选中的表格条目
  selectItems: [],

  list: [],

  // -------- 字典 --------
  // 类型列表
  typeList: [
    { id: 1, name: '格式转换' },
    { id: 2, name: '迁移' }
  ]
};

const ConversionContext = createContext();

const ConversionProvider = (props) => {
  const [state, dispatch] = useReducer(ConversionReducer, initialState);

  const actions = {
    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     * @return {*}
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 获取格式转换登记列表
     * @param {IPageQuery<IRegConversionListParams>} query
     * @return {*}
     */
    getRegConversionList(query) {
      return new Promise((resolve, reject) => {
        fetchRegConversionListByPage(query)
          .then((res) => {
            const { data } = res;
            console.log('pending', data);
            dispatch({
              type: SET_REG_CONVERSION_LIST,
              data: data.results
            });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 增加格式转换登记
     * @param {IAddRegConversionParams} params
     * @return {any}
     */
    addRegConversionFunc(params) {
      return new Promise((resolve, reject) => {
        addRegConversion(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_REG_CONVERSION, data, id: data.id });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 编辑格式转换登记
     * @param {IEditRegConversionParams} params
     * @return {any}
     */
    editRegConversionFunc(params) {
      return new Promise((resolve, reject) => {
        editRegConversion(params)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_REG_CONVERSION, data, id: data.id });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 删除登记条目
     * @param {number|number[]} id
     * @param {string} title
     */
    deleteItem(id, title = '是否移除选中的条目?') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteRegConversionItem(ids).then((res) => {
            const data = res.data.map((id) => parseInt(id, 10));
            message.success('删除成功');
            dispatch({ type: DELETE_REGISTRATION_ITEM, ids: data });
          });
        },
        onCancel() {
          console.log('del item Cancel');
        }
      });
    }
  };

  const filters = {
    typeFilter(id) {
      return state.typeList.find((item) => item.id === id)?.name || '-';
    }
  };

  useEffect(() => {}, []);

  return (
    <ConversionContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </ConversionContext.Provider>
  );
};

export const useConversionContext = () => {
  return useContext(ConversionContext);
};

export { ConversionContext, ConversionProvider };
